package com.ray.business.api;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.ray.base.service.compose.GoodsService;
import com.ray.base.table.entity.BaseMaterialModel;
import com.ray.base.table.vo.material.model.MaterialModelVO;
import com.ray.business.builder.BusinessGoodsVOBuilder;
import com.ray.business.builder.BusinessQuickInBuilder;
import com.ray.business.builder.PrintDataBuilder;
import com.ray.business.service.ProdBusinessQuickInService;
import com.ray.business.service.ProdBusinessQuickService;
import com.ray.business.service.ProdOrderGoodsService;
import com.ray.business.service.ProdOrderStepService;
import com.ray.business.service.compose.IndexService;
import com.ray.business.table.entity.ProdBusinessQuick;
import com.ray.business.table.entity.ProdBusinessQuickIn;
import com.ray.business.table.entity.ProdOrderGoods;
import com.ray.business.table.entity.ProdOrderStep;
import com.ray.business.table.params.business.quick.BusinessQuickInParams;
import com.ray.business.table.vo.BusinessGoodsVO;
import com.ray.common.check.AbstractCheck;
import com.ray.common.dto.PrintDataDTO;
import com.ray.template.TemplateFactory;
import com.ray.template.TemplateRecord;
import com.ray.util.CodeSplitUtil;
import com.ray.validate.support.utils.ValidateUtil;
import com.ray.woodencreate.beans.LoginUser;
import com.ray.woodencreate.exception.BusinessExceptionFactory;
import com.ray.woodencreate.result.MsgCodeConstant;
import com.ray.woodencreate.result.Result;
import com.ray.woodencreate.result.ResultFactory;
import com.ray.woodencreate.util.LogInUserUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author bo shen
 * @Description: 订单相关服务
 * @Class: BusinessApi
 * @Package com.ray.base.api
 * @date 2020/5/27 11:15
 * @company <p>Ray快速开发平台</p>
 * @updateRecord time(修改时间)  author(修改人)   desc(修改内容)
 */
@Service
@Slf4j
public class BusinessQuickInApi {

    @Autowired
    private ProdBusinessQuickInService prodBusinessQuickInService;
    @Autowired
    private GoodsService goodsService;
    @Autowired
    private ProdBusinessQuickService prodBusinessQuickService;
    @Autowired
    private ProdOrderGoodsService prodOrderGoodsService;
    @Autowired
    private ProdOrderStepService prodOrderStepService;
    @Autowired
    private IndexService indexService;

    @Transactional
    public Result<String> saveQuickIn(BusinessQuickInParams businessQuickInParams) {
        ValidateUtil.validate(businessQuickInParams);
        ValidateUtil.validate(businessQuickInParams.getRealQuantity(),"实际数量不能为空");
        //当前登录对象
        LoginUser loginUser = LogInUserUtil.get();

        ProdBusinessQuick prodBusinessQuick = prodBusinessQuickService.queryBusinessQuickByQuickCode(businessQuickInParams.getQuickCode(), loginUser);
        new AbstractCheck<>(prodBusinessQuick).checkNull("快捷入库单不存在");
        BusinessQuickInBuilder businessQuickInBuilder = new BusinessQuickInBuilder();

       //判断是否是最后一个工序 最后一个工序自动生成顺序
       ProdOrderStep prodOrderStep = prodOrderStepService.lastStep(CodeSplitUtil.getFirst(prodBusinessQuick.getGoodsCode()),loginUser);
       if(StrUtil.equals(prodOrderStep.getStepCode(),prodBusinessQuick.getStepCode())){
           businessQuickInParams.setIndexSort(indexService.queryIndex(prodBusinessQuick.getOrderNo(),CodeSplitUtil.getFirst(prodBusinessQuick.getGoodsCode()),loginUser));
       }
        //判断序列号是否存在
        if (StrUtil.isNotBlank(businessQuickInParams.getSerialNumber())) {
            ProdBusinessQuickIn serialNumberIn = prodBusinessQuickInService.listByQuickCodeAndSerialNumber(businessQuickInParams.getQuickCode(), businessQuickInParams.getSerialNumber(), loginUser);
            if (ObjectUtil.isNotNull(serialNumberIn)) {
                throw BusinessExceptionFactory.newException("序列号已经存在");
            }
        }
        businessQuickInBuilder.append(businessQuickInParams).appendOutCode(businessQuickInParams.getCode())
                .append(prodBusinessQuick).appendCreate(loginUser);
        prodBusinessQuickInService.save(businessQuickInBuilder.bulid());
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000001, businessQuickInBuilder.getCode());

    }


    @Transactional
    public Result<String> deleteQuickIn(String code) {
        //当前登录对象
        LoginUser loginUser = LogInUserUtil.get();
        ProdBusinessQuickIn prodBusinessQuickIn =  prodBusinessQuickInService.getEntityByCode(code,loginUser);
        new AbstractCheck<>(prodBusinessQuickIn).checkNull("记录不存在");
        BusinessQuickInBuilder businessQuickInBuilder = new BusinessQuickInBuilder();
        businessQuickInBuilder.appendCode(code).appendEdit(loginUser).delete();
        prodBusinessQuickInService.edit(businessQuickInBuilder.bulid(), loginUser);
        //插入被废弃的顺序
        indexService.saveDeleteIndex(prodBusinessQuickIn.getOrderNo(),CodeSplitUtil.getFirst(prodBusinessQuickIn.getGoodsCode()),prodBusinessQuickIn.getIndexSort(),loginUser);
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000001, businessQuickInBuilder.getCode());

    }

    @Transactional
    public Result<List<BusinessGoodsVO>> listInRecord(String quickCode) {
        //当前登录对象
        LoginUser loginUser = LogInUserUtil.get();
        List<ProdBusinessQuickIn> quickIns = prodBusinessQuickInService.listByQuickCode(quickCode, loginUser);
        Map<String, MaterialModelVO> modelMap = new HashMap<>();

        List<BusinessGoodsVO> goods = quickIns.parallelStream().map(prodBusinessQuickIn -> {
            BusinessGoodsVOBuilder businessGoodsVOBuilder = new BusinessGoodsVOBuilder();
            MaterialModelVO materialModelVO = modelMap.get(prodBusinessQuickIn.getGoodsCode());
            if (ObjectUtil.isNull(materialModelVO)) {
                materialModelVO = goodsService.queryGoodsByCode(prodBusinessQuickIn.getGoodsCode(), loginUser);
                modelMap.put(prodBusinessQuickIn.getGoodsCode(), materialModelVO);
            }
            businessGoodsVOBuilder.append(materialModelVO);
            businessGoodsVOBuilder.append(prodBusinessQuickIn);
            return businessGoodsVOBuilder.bulid();
        }).collect(Collectors.toList());
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000001, goods);

    }


    /**
     * 查询商品信息
     *
     * @param code
     * @return
     */
    public Result<List<TemplateRecord>> printData(String code) {
        LoginUser loginUser = LogInUserUtil.get();
        //查询商品信息
        ProdBusinessQuickIn prodBusinessQuickIn = prodBusinessQuickInService.getEntityByCode(code, loginUser);
        new AbstractCheck<>(prodBusinessQuickIn).checkNull("记录不存在");
        //查询商品信息
        MaterialModelVO materialModelVO = goodsService.queryGoodsByCode(prodBusinessQuickIn.getGoodsCode(), loginUser);
        //查询订单商品信息
        ProdOrderGoods prodOrderGoods = prodOrderGoodsService.queryOrderGoodsByGoodsCode(prodBusinessQuickIn.getOrderNo(), prodBusinessQuickIn.getGoodsCode(), loginUser);
        //打印对象信息
        PrintDataDTO printDataDTO = new PrintDataBuilder().append(materialModelVO).append(prodBusinessQuickIn).append(prodOrderGoods).bulid();
        List<TemplateRecord> records = new TemplateFactory<>().readTemplate(printDataDTO);
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000002, records);
    }
}
